import { getHistoryDataList } from "@/api/modules/iot/data";
import BaseChart from "@/components/Chart/BaseChart.vue";
import { DataChart } from "@/components/Chart/interface";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { shortcuts } from "@/hooks/useTime";
import { SchemaNodeKey } from "@/utils/constants";
import { parseProfileFromSn } from "@/utils/schema";
import moment from "moment";
import { defineComponent } from "vue";
export default defineComponent({
	props: {
		title: String,
		dataValue: [String, Number, Object, Array],
		dataKey: {
			type: String,
			default() {
				//key path: k1, k1.k1_1
				return "k1";
			}
		}
	},
	emits: [],
	setup(props, { attrs }) {
		const chartView = ref<any>();
		const viewType = ref<string>();
		const viewTypeList = ref<{ label: string; value: string }[]>([
			{ label: "图表", value: "chart" },
			{ label: "列表", value: "list" }
		]);
		const proTable = ref<any>();
		const profile = inject<any>(SchemaNodeKey.profile);
		const sn = parseProfileFromSn(profile.value);
		let dataList: any = [];
		const active = ref<string>("");
		const stats = reactive<any>({
			timeRange: [moment().format("YYYY-MM-DD 00:00:00"), moment().format("YYYY-MM-DD 23:59:59")]
		});
		if (typeof props.dataValue == "number") {
			viewType.value = "chart";
		} else {
			viewType.value = "list";
		}

		const feachHistory = async () => {
			let { result } = await getHistoryDataList({
				idSn: sn,
				key: props.dataKey,
				keyType: "sensor", //sensor、system,
				startTime: stats.timeRange[0]
					? moment(stats.timeRange[0]).format("YYYY-MM-DD HH:mm:ss")
					: moment().format("YYYY-MM-DD 00:00:00"),
				endTime: stats.timeRange[1]
					? moment(stats.timeRange[1]).format("YYYY-MM-DD HH:mm:ss")
					: moment().format("YYYY-MM-DD 23:59:59")
			});
			dataList = result || [];
		};
		const changeView = async () => {
			await feachHistory();
			nextTick(() => {
				if (viewType.value == "chart") {
					convertChart();
				} else {
					proTable.value.getTableList();
				}
			});
		};
		watchEffect(() => {
			active.value = props.dataKey;
			changeView();
		});
		const convertChart = () => {
			//转换成图表需要的数据格式
			//测试数据
			// let dataList = [
			// 	{
			// 		devSn: "device000001",
			// 		id: 1,
			// 		updateTime: "2023-02-14 09:19:25",
			// 		value: 23.2
			// 	},
			// 	{
			// 		devSn: "device000001",
			// 		id: 1,
			// 		updateTime: "2023-02-14 09:20:25",
			// 		value: 23.2
			// 	}
			// ];
			let chartData: DataChart.DataList = { dataList: [] };
			dataList.map((item: any) => {
				item.valKey = active.value;
				let dts = moment(item.updateTime);
				let time = dts.isValid() ? dts.format("HH:mm:ss") : item.updateTime;
				chartData.dataList.push({ time: time, value: item.value });
			});
			let seen = new Map();
			chartData.dataList = chartData.dataList.filter((item: any) => {
				return !seen.has(item.time) && seen.set(item.time, 1);
			});
			chartView.value.setData(chartData);
		};
		const columns: ColumnProps[] = [
			{ prop: "devSn", label: "设备" },
			{ prop: "key", label: "变量" },
			{ prop: "updateTime", label: "时间" },
			{ prop: "value", label: "数据值" }
		];
		const getTableList = async () => {
			return { result: { records: dataList } };
		};
		const dataCallback = (param: any) => {
			return { datalist: param.records };
		};
		return () => {
			return (
				<div>
					<div class="flex justify-between p-4">
						<div class="pl-4">
							<el-radio-group v-model={viewType.value} onChange={() => changeView()} size="large">
								{viewTypeList.value.map(item => {
									return <el-radio label={item.value}>{item.label}</el-radio>;
								})}
							</el-radio-group>
						</div>
						<div>
							<span class="pr-2">时间范围</span>
							<el-date-picker
								v-model={stats.timeRange}
								style="width:340px"
								type="datetimerange"
								shortcuts={shortcuts()}
								range-separator="至"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
							/>
							<el-button class="iconfont iconbx-sync" style="margin-top:-5px" onClick={() => feachHistory()}>
								查询
							</el-button>
						</div>
					</div>
					{viewType.value == "chart" ? (
						<BaseChart class="pl-4 pr-4 bg-white" ref={chartView} {...attrs} />
					) : (
						<div style="height:55vh">
							<ProTable
								ref={proTable}
								showHeader={false}
								columns={columns}
								requestApi={getTableList}
								dataCallback={dataCallback}
								pagination={false}
							></ProTable>
						</div>
					)}
				</div>
			);
		};
	}
});
